package dmdemo

import (
	"fmt"
	"strconv"
	"sync"
	"time"
)

type DataTest struct {
	Thread             int //线程数
	DataLen            int //数据量
	MaxOneTimeDealData int
}

// AddDataTest NewCar 是 Car 的构造函数
func AddDataTest(thread, len, maxOneTimeDealData int) *DataTest {
	return &DataTest{
		Thread:             thread,
		DataLen:            len,
		MaxOneTimeDealData: maxOneTimeDealData,
	}
}

// Run Display 为 Car 类定义一个方法，用来显示汽车的信息
func (c *DataTest) Run() {
	InitDB()
	size := 1000
	total := 2500000000 / size
	threadCount := 100
	batchSize := total / threadCount

	fmt.Printf("total=%d, threadCount:%d\n", total, threadCount)

	var wg sync.WaitGroup
	var mu sync.Mutex
	progress := 0
	count := 0

	startTime := time.Now()

	for t := 0; t < threadCount; t++ {
		wg.Add(1)
		go func(t int) {
			defer wg.Done()
			for i := 0; i < batchSize; i++ {
				tds := GenerateTerminalDataArray(100, size)
				InsertInBatchesTerminalData(tds)
				mu.Lock()
				progress++
				count += size
				midTime := time.Now()
				midDuration := midTime.Sub(startTime)
				h := int(midDuration.Hours())
				m := int(midDuration.Minutes()) % 60
				s := int(midDuration.Seconds()) % 60
				countStr := strconv.FormatInt(int64(count), 10)
				countWithCommas := addCommas(countStr)
				//fmt.Printf("%s :Progress duration for %d:%d:%d -%s %.2f%% \r\n", time.Now().Format("2006-01-02 15:04:05"), h, m, s, countWithCommas, float64(progress)/float64(total)*100)
				fmt.Printf("%s :Progress duration for %03d:%02d:%02d -%s %.2f%% \r\n", time.Now().Format("2006-01-02 15:04:05"), h, m, s, countWithCommas, float64(progress)/float64(total)*100)
				mu.Unlock()
			}
		}(t)
	}

	wg.Wait()

	endTime := time.Now()
	totalDuration := endTime.Sub(startTime)
	h := int(totalDuration.Hours())
	m := int(totalDuration.Minutes()) % 60
	s := int(totalDuration.Seconds()) % 60
	fmt.Printf("Total duration: %d:%d:%d\n", h, m, s)
}

func addCommas(nStr string) string {
	n := len(nStr)
	if n <= 3 {
		return nStr
	}
	return addCommas(nStr[:n-3]) + "," + nStr[n-3:]
}
